<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use App\Common\ValidateHandler;
use App\Models\BaseModel;
use App\Models\Admin\Menu;
use App\Models\Admin\Rule;
use App\Models\Admin\Store;
use App\Models\Admin\Admin;

class Role extends BaseModel
{
    protected $fillable = [
        'id', 'title', 'describe', 'status', 'store_id',
        'menu_ids', 'half_menu_ids', 'rule_ids', 'created_at', 'updated_at'
    ];

    public function getList($pageSize)
    {
        $data = $this->orderBy('created_at', 'desc')->paginate($pageSize)->toArray();
        $data = $this->handleData($data);

        return $this->success($data);
    }

    public function getAllRole()
    {
        $data = $this->get()->toArray();

        return $this->success($data);
    }

    private function handleData($data)
    {
        $store = new Store;
        $stores = $store->select(['id', 'title'])->get()->toArray();
        $stores = key_val($stores);
        $stores[0] = ['id' => 0, 'title' => '无店铺'];

        foreach ($data['data'] as $k => $role) {
            $data['data'][$k]['store'] = $stores[$role['store_id']];
        }

        return $data;
    }

    //用户获取设置角色权限菜单树
    public function getAllMenuNodes()
    {
        $data = Menu::orderBy('next', 'asc')->orderBy('level', 'asc')->orderBy('sort', 'desc')->get()->toArray();

        $arr = [];
        foreach ($data as $menu) {
            $item = [];
            $item['id'] = $menu['id'];
            $item['pid'] = $menu['pid'];
            $item['label'] = $menu['title'];
            $item['level'] = $menu['level'];
            $item['type'] = 'menu';

            if ($menu['level'] == 0) {
                // 主节点 直接push到arr中
                $item['children'] = []; //子节点
                $arr['m-'.$menu['id']] = $item;
            } else {
                $rules = Rule::where('menu_id', $item['id'])->get()->toArray();
                $rules = $this->getMenuRule($rules);
                $item['children'] = $rules;

                // 从节点 push到clild中
                array_push($arr['m-'.$menu['pid']]['children'], $item);
            }
        }

        return $this->success($arr);
    }

    private function getMenuRule($data)
    {
        $arr = [];
        foreach ($data as $rule) {
            $item = [];
            $item['id'] = $rule['id'];
            $item['type'] = 'rule';
            $item['label'] = $rule['title'];

            array_push($arr, $item);
        }

        return $arr;
    }

    public function handle($data)
    {
        $result = $this->validate($data);
        if(!$result['res']) {
            return $this->error($result);
        }

        if ($data['id'] == 'new') {
            unset($data['id']);
            $this->create($data);
        } else {
            $id = $data['id'];
            $this->where('id', $id)->update($data);
        }

        return $this->success(['info' => '操作成功']);
    }

    private function validate($data){
        $arr = [
            0 => [
                'name' => '角色名称',
                'value' => $data['title'],
                'func' => 'is_empty'
            ],
            2 => [
                'name' => '角色描述',
                'value' => $data['describe'],
                'func' => 'is_empty'
            ]
        ];

        return ValidateHandler::do($arr);
    }

    public function getStore()
    {
        $store = new Store;
        $data = $store->select(['id', 'title'])->get()->toArray();
        array_unshift($data, ['id' => 0, 'title' => '无店铺']);

        return $this->success($data);
    }

    public function getRoles()
    {
        $data = $this->where('status', '!=', 0)->get()->toArray();

        return $this->success($data);
    }

    public function deleteAction($id)
    {
        //如果角色被用户使用，不可删除
        $adminCount = Admin::where('role_id', $id)->count();
        if ($adminCount > 0) {
            return $this->error(['info' => '请删除此角色对应的用户后再来删除']);
        }

        $this->where('id', $id)->delete();
        return $this->success(['info' => '操作成功']);
    }
}
